import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { defalutImg, geti4CityNameById } from 'src/app/comm';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { UserLabelAddComponent } from '../../../sharedModule/commponent/user-label-add/user-label-add.component';
import { CustomerBasicsService } from './customer-basics.service';
import { ConfigDictListService } from '../../config/config-dict-list/config-dict-list.service'
import { CustomerGrowthService } from '../customer-growth/customer-growth.service';
import { CommonService } from 'src/app/services-common/common.service';
import { PermissionService } from '../../../service/permission.service';

@Component({
    selector: 'app-customer-basics',
    templateUrl: './customer-basics.component.html',
    styleUrls: ['./customer-basics.component.scss']
})
export class CustomerBasicsComponent implements OnInit {
    @ViewChild('fansModal') fansModal: any;

    /**
     * id
     */
    id: any = 0;
    /**
     * 详情数据
     */
    detailsData: any = {};
    /**
     * 全局 loading
     */
    messageId: any = null;
    // 字典类集合
    dictSet: any = {
        // 平台集合
        platform: {}
    }
    /**
     * 加载失败显示图像占位符
     */
    fallback: string = defalutImg;

    // 账户信息
    accountInfos: any = {};

    // 成长值明细 Modal
    isGrowupVisible: boolean = false;
    tableParams: any = {
        tableLoading: false,
        page: 1,
        pageSize: 10,
        total: 0
    };
    growupTableData: any = [];

    // 成长值options
    growthValueOptions: any = [];

    // 权限管理options
    roleOptions = [
        { label: '限制使用', value: 0, checked: false, tip: '勾选后用户将被限制使用' },
        { label: '爱思回收', value: 1, checked: false, tip: '勾选后用户将不能回收手机' },
        { label: '二手商城', value: 2, checked: false, tip: '勾选后用户将不能购买二手手机' },
        { label: '配件商城', value: 3, checked: false, tip: '勾选后用户将不能购买配件商城商品' },
        { label: '爱思定制', value: 4, checked: false, tip: '勾选后用户将不能定制手机壳，购买定制券，发定制券红包' },
    ];
    roleExhibitionOptions: any = [];
    isRoleVisible: boolean = false;
    roleSubLoading: boolean = false;
    
    constructor(
        private activatedRoute: ActivatedRoute,
        private message: NzMessageService,
        private CustomerBasicsService: CustomerBasicsService,
        private DictService: ConfigDictListService,
        private customerGrowthService: CustomerGrowthService,
        private commonService: CommonService,
        private nzModalService: NzModalService,
        public permission: PermissionService
    ) { }

    ngOnInit() {
        this.activatedRoute.params.subscribe(params => {
            this.id = params.id;
        });
        this.getGrowthValueOptions(); // 成长值
        this.details();
        this.httpDict();
    }
    /**
     * 获取详情
     */
    details() {
        this.CustomerBasicsService.details({ id: this.id }).subscribe((res: any) => {
            const { list, data } = res.data || {}
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            if (list.length > 0) {
                this.detailsData = list[0]
            }
            this.accountInfos = data || {};
            
            // 用户权限
            this.roleExhibitionOptions = [];
            this.roleOptions.filter((item: any) => {
                if (this.accountInfos?.jurisdiction.includes(item.value)) {
                    this.roleExhibitionOptions.push({
                        ...item,
                        checked: true
                    })
                }
            });
        }, err => {
            this.createMessage("error", err.message);
        })
    }
    httpDict() {
        const params = {
            // 名称或者编码搜索
            parentKey: "channel",
            // 多少页，默认1
            pageNum: 1,
            // 每页多少条，默认10
            pageSize: 999
        }
        this.DictService.getDictList(params).subscribe((res: any) => {
            const { data } = res
            const { list } = data || {}
            const { records } = list || {}
            records?.forEach((item: any) => {
                this.dictSet.platform[item.content] = item.name
            });
        })
    }

    /**
     * 状态转文字
     * @param state 
    */
    state_To_text(state: any) {
        let text = "";
        switch (parseInt(state)) {
            case 0:
                text = "无效";
                break;
            case 1:
                text = "有效";
                break;
            case 2:
                text = "禁用";
                break;
            default:
                text = "-";
                break;
        }
        return text;
    }
    // 性别
    sex_to_text(val: any) {
        const text: any = { 1: '男', 2: '女' }
        return text[val] || '-'
    }
    // 平台
    platform_to_text(val: any) {
        return this.dictSet.platform[val] || '-'
    }
    /**
     * 开启loading
     */
    createBasicMessage(): void {
        this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
    }
    /**
     * 移除loading
     */
    removeBasicMessage() {
        this.message.remove(this.messageId);
        this.messageId = null;
    }
    /**
     * 全局展示操作反馈信息
     * @param type 其他提示类型 success:成功 error:失败 warning：警告
     */
    createMessage(type: any, str: any): void {
        this.message.create(type, str);
    }

    // 用户真实身份
    userIdentityFilter(state: any) {
        switch (parseInt(state)) {
            case 0:
                return '未选择';
            case 1:
                return '个人';
            case 2:
                return '门店商户';
            case 3:
                return '个人商户';
            default:
                return '-';
        }
    }

    // 用户初始身份
    temUserType_To_text(state: any) {
        switch (parseInt(state)) {
            case 0:
                return '未选择';
            case 1:
                return '个人';
            case 2:
                return '门店商户';
            case 3:
                return '个人商户';
            default:
                return '-';
        }
    }

    // 查看粉丝
    showFans() {
        this.fansModal.isFansVisible = true;
    }

    // 地区filter
    geti4CityNameFilter() {
        let tmpObj = geti4CityNameById(this.detailsData.city);
        return tmpObj?.name || '';
    }

    /**
     * ----------------------------------------------------------------
     * 成长值明细 Modal
     * ----------------------------------------------------------------
     */
    showGrowupModal() {
        this.loadGrowupTable();
        this.isGrowupVisible = true;
    }
    loadGrowupTable() {
        let params = {
            userId: this.id,
            page: this.tableParams.page,
            pageSize: this.tableParams.pageSize
        }
        this.tableParams.tableLoading = true;
        this.customerGrowthService.memberValueTableData(params).subscribe((res: any) => {
            this.tableParams.tableLoading = false;
            
            if (res.code == 0) {
                const { records, total } = res.data;
        
                this.growupTableData = records || [];
                this.tableParams.total = total || 0;
            } else {
                this.message.error(res.message);
            }
            
        }, (error: any) => {
            this.growupTableData = [];
            this.tableParams.total = 0;
            this.tableParams.tableLoading = false;
        })
    }
    // Change page
    onPageIndexChange(index: number) {
        this.tableParams.page = index;
        this.loadGrowupTable();
    }
    // Change pageSize
    onPageSizeChange(sizeNum: number) {
        this.tableParams.page = 1;
        this.tableParams.pageSize = sizeNum;
        this.loadGrowupTable();
    }

    // 成长值options
    async getGrowthValueOptions() {
        const res: any = await this.commonService.dictListData('type_integral');
        if (res.code == 0) {
            this.growthValueOptions = res.data.list || [];
        } else {
            this.growthValueOptions = [];
            this.message.error(res.message);
        }
    }
    // 成长值类型文字filter
    growupTypeFilter(type: any) {
        let tempObj: any = this.growthValueOptions.find((item: any) => {
            return item.content == type;
        })
        return tempObj?.name || '-';
    }

    /**
     * ----------------------------------------------------------------
     * 用户权限管理 Modal
     * ----------------------------------------------------------------
     */
    showRoleModal() {
        if (this.accountInfos?.jurisdiction && this.accountInfos?.jurisdiction.length) {
            this.roleOptions.forEach((item: any) => {
                if (this.accountInfos?.jurisdiction.includes(item.value)) {
                    item.checked = true;
                } else {
                    item.checked = false;
                }
            })
        } else {
            this.roleOptions.forEach((item: any) => {
                item.checked = false;
            })
        }
        
        this.isRoleVisible = true;
    }
    async subRoleData() {
        let params: any = {
            userId: this.id,
            list: []
        }
        params.list = this.conversionObj(this.roleOptions);
        this.roleSubLoading = true;
        const res: any = await this.CustomerBasicsService.updateRoleData(params);
        this.roleSubLoading = false;

        if (res.code === 0) {
            this.isRoleVisible = false;
            this.message.success('操作成功');
            this.details();
        } else {
            this.message.error(res.message);
        }
    }

    // 数组转化
    conversionObj(arr: Array<any>) {
        let tempArr: Array<any> = [];
        tempArr = arr.map((item: any) => {
            return {
                key: item.value,
                value: item.checked
            }
        });
        return tempArr;
    }

    // 打标
    addLabel(userId: any) {
        const modal = this.nzModalService.create({
            nzTitle: '用户打标',
            nzContent: UserLabelAddComponent,
            nzFooter: null,
            nzWidth: '400px',
            nzMaskClosable: false,
            nzComponentParams: {
                userId
            },
        });
        modal.afterClose.subscribe((res: any) => {
            if (res && res.refresh) {
                this.details();
            }
        });
    }
}
